package whatever;

import java.util.List;

public class T92 {


    public static class ListNode {
       int val;
       ListNode next;
       ListNode() {}
       ListNode(int val) { this.val = val; }
       ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }

    public static ListNode reverseBetween2(ListNode head, int left, int right) {
        if(head == null || head.next == null || left == right) {
            return head;
        }

        int flag = left;

        int frontIndex = 1;
        ListNode frontNode = head;
        ListNode beginNode = head;
        if (1 != left) {
            while (left != frontIndex + 1) {
                frontNode = frontNode.next;
                frontIndex++;
            }
            beginNode = frontNode.next;
        }

        ListNode nextNode = beginNode.next;
        ListNode curNode = beginNode.next;
        ListNode tmpNode = beginNode;
        while (left != right && nextNode != null) {
            nextNode = curNode.next;
            curNode.next = tmpNode;
            tmpNode = curNode;
            curNode = nextNode;
            left++;
        }

        if (flag != 1) {
            frontNode.next = tmpNode;
        } else {
            head = tmpNode;
        }

        if (nextNode != null) {
            beginNode.next = nextNode;
        } else {
            beginNode.next = null;
        }
        return head;
    }

    public static ListNode reverseBetween(ListNode head, int left, int right)   {
        ListNode virtualHead = new ListNode();
        virtualHead.next = head;
        ListNode frontNode = virtualHead;

//        frontNode步到reverse的起点
        for (int i = 0; i < left - 1; i++) {
            frontNode = frontNode.next;
        }
//        开始reverse
        ListNode curNode = frontNode.next;
        ListNode nextNode =  curNode.next;
        for (int i = left; i < right; i++) {
            nextNode = curNode.next;
            curNode.next = nextNode.next;
//             = curNode;
            curNode = nextNode;
        }
        return virtualHead.next;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        ListNode l2 = new ListNode(2);
//        ListNode l3 = new ListNode(3);
//        ListNode l4 = new ListNode(4);
//        ListNode l5 = new ListNode(5);
        head.next = l2;
//        l2.next = l3;
//        l3.next = l4;
//        l4.next = l5;

        ListNode res = reverseBetween(head, 1, 2);
        System.out.println(res.toString());
    }

}
